//
//  ShopCartViewController.m
//  1243
//
//  Created by 我的 on 16/4/18.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "ShopCartViewController.h"

#import "ShopCartCell.h"

#import "ShopCartToolbar.h"
#import "QueRenDingDanViewController.h"
#import "ReadLoginData.h"
#import "UIImageView+WebCache.h"
#import "ShopCartHeaderCell.h"
#import "MBProgressHUD.h"
#import "ShopMainViewController.h"

@interface ShopCartViewController ()<UITableViewDelegate, UITableViewDataSource, ShopCartToolbarDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, assign) NSInteger num;

@property (nonatomic, strong) NSMutableArray *shopArrM;

@property (nonatomic, strong) NSMutableArray *dingDanArrM;

@property (nonatomic, assign) CGFloat allPrice;

//添加下方的工具栏
@property (nonatomic, strong)ShopCartToolbar *toolBar;
//设置全选按钮的bool
@property (nonatomic, assign) BOOL allJudge;

@property (nonatomic, strong) NSMutableArray *cellArrM;

@property (nonatomic, strong) NSMutableArray *headerArrM;

@property (nonatomic, strong) UIButton *editBtn;

@end

@implementation ShopCartViewController

- (UITableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 49) style:UITableViewStyleGrouped];
    }
    return _tableView;
}

- (NSMutableArray *)shopArrM {
    
    if (!_shopArrM) {
        _shopArrM = [NSMutableArray array];
    }
    return _shopArrM;
}

- (NSMutableArray *)cellArrM {
    
    if (!_cellArrM) {
        _cellArrM = [NSMutableArray array];
    }
    return _cellArrM;
}

- (NSMutableArray *)headerArrM {
    if (!_headerArrM) {
        _headerArrM = [NSMutableArray array];
    }
    return _headerArrM;
}

- (NSMutableArray *)dingDanArrM {
    
    if (!_dingDanArrM) {
        _dingDanArrM = [NSMutableArray array];
    }
    return _dingDanArrM;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.allJudge = YES;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.title = @"购物车";
    [self.tableView registerNib:[UINib nibWithNibName:@"ShopCartCell" bundle:nil] forCellReuseIdentifier:@"ShopCartCell"];
    
    self.tableView.tableFooterView = [UIView new];
    
    [self.view addSubview:self.tableView];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImage:nil highImage:nil target:self action:@selector(clickEditBtn:) forControlEvents:UIControlEventTouchUpInside title:@"编辑"];
    
    
    [self addFootToolView];
}

- (void)clickEditBtn:(UIButton *)item {
    self.editBtn = item;
    [item setTitle:@"完成" forState:UIControlStateSelected];
    item.selected = !item.selected;
    self.toolBar.payButton.selected = item.selected;
    self.toolBar.selectButton.selected = !item.selected;
    if (self.toolBar.payButton.selected) {
        [self.toolBar.payButton setTitle:@"删除" forState:UIControlStateNormal];
    } else {
        [self.toolBar.payButton setTitle:@"去结算" forState:UIControlStateNormal];
    }
    self.allJudge = !item.selected;
    [self.cellArrM removeAllObjects];
    [self.headerArrM removeAllObjects];
    [self.tableView reloadData];
    [self totalPrice];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    NSArray *arr = [ReadLoginData readShopArr];
    
    [self.shopArrM addObjectsFromArray:arr];
    [self.dingDanArrM addObjectsFromArray:arr];
    [self totalPrice];
}

//添加工具条
- (void)addFootToolView {
        
    ShopCartToolbar *toolbar = [[ShopCartToolbar alloc] initWithFrame:CGRectMake(0, HIGHT-49, WEITH, 49)];
    toolbar.delegate = self;
    
    self.toolBar = toolbar;
    [self.view addSubview:self.toolBar];
    //计算总价
    [self totalPrice];
    
}

- (void)totalPrice {
    NSInteger i = 0;
    if (self.allJudge) {
        for (NSArray *arr in self.shopArrM) {
            for (NSDictionary *dic in arr) {
                self.allPrice = self.allPrice + [dic[@"SellPrice"] floatValue] * [dic[@"buyNum"] integerValue];
            }
        }
    } else {
        for (ShopCartCell *cell in self.cellArrM) {
            if (cell.selectBtn.selected) {
                NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
                self.allPrice = self.allPrice + [self.shopArrM[indexPath.section][indexPath.row][@"SellPrice"] floatValue] * [self.shopArrM[indexPath.section][indexPath.row][@"buyNum"] integerValue];
            }
            i ++;
        }
    }
    
    [self.toolBar.totalPriceView setTitle:[NSString stringWithFormat:@"%.2f", self.allPrice] forState:UIControlStateNormal];

    self.allPrice = 0;
}

#pragma mark -- ShopCartToolbarDelegate
- (void)shopCartToolBar:(UIView *)toolBar didClickButton:(UIButton *)button {
    
    switch (button.tag) {
        case 0:
        {
            NSLog(@"点击了选择按钮");
            self.allJudge = !self.allJudge;
            button.selected = self.allJudge;
            [self.cellArrM removeAllObjects];
            [self.headerArrM removeAllObjects];
            [self totalPrice];
            [self.tableView reloadData];
        }
            break;
        case 1:
        {
            NSLog(@"点击了第二个按钮");
        }
            break;
        case 2:
        {
            NSLog(@"点击了结算按钮");
            
            if (self.shopArrM.count == 0) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"购物车没有商品，赶快去买吧！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alert.tag = 10022;
                [alert show];
                return;
            }
            [self.dingDanArrM removeAllObjects];
            NSInteger i = 0;
            for (ShopCartCell *cell in self.cellArrM) {
                if (cell.selectBtn.selected) {
                    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
                    [self.dingDanArrM addObject:self.shopArrM[indexPath.section][indexPath.row]];
#warning -------------一个bug
                    self.shopArrM[indexPath.section][indexPath.row][@"isPay"] = @"1";
                    [ReadLoginData saveShopDataToLocal:self.shopArrM];
                } else {
                    
                }
                i ++;
                NSLog(@"i == %ld", i);
            }
            if (button.selected) {
                NSLog(@"...");
                for (ShopCartCell *cell in self.cellArrM) {
                    if (cell.selectBtn.selected) {
                        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
                        if ([self.shopArrM[indexPath.section] count] == 1) {
                            [self.shopArrM removeObjectAtIndex:indexPath.section];
                        } else {
                            [self.shopArrM[indexPath.section] removeObjectAtIndex:indexPath.row];
                        }
                        [ReadLoginData saveShopDataToLocal:self.shopArrM];
                    }
                }
                [self.tableView reloadData];
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
                hud.mode = MBProgressHUDModeCustomView;
                UIImage *image = [[UIImage imageNamed:@"Checkmark"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
                hud.customView = [[UIImageView alloc] initWithImage:image];
                hud.square = YES;
                hud.label.text = NSLocalizedString(@"删除成功", @"HUD done title");
                [hud hideAnimated:YES afterDelay:1.f];
                [self clickEditBtn:self.editBtn];
                return;
            }
            QueRenDingDanViewController *dingDanVC = [[QueRenDingDanViewController alloc] init];
            dingDanVC.dingDanArrM = [NSMutableArray array];
            [dingDanVC.dingDanArrM addObjectsFromArray:self.dingDanArrM];
            dingDanVC.allPrice = [self.toolBar.totalPriceView.titleLabel.text floatValue];
            dingDanVC.num = 1;
            [self.navigationController pushViewController:dingDanVC animated:YES];
            
            [self.shopArrM removeAllObjects];
            [self.dingDanArrM removeAllObjects];

            break;
        }
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableView DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.shopArrM.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *arr = self.shopArrM[section];
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ShopCartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShopCartCell" forIndexPath:indexPath];
    
    if (!cell) {
        cell = [[ShopCartCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ShopCartCell"];
    }
    
    cell.titleLabel.text = self.shopArrM[indexPath.section][indexPath.row][@"Title"];
    cell.shopPrice.text = [NSString stringWithFormat:@"￥%@",self.shopArrM[indexPath.section][indexPath.row][@"SellPrice"]];
    cell.buyNum.text = self.shopArrM[indexPath.section][indexPath.row][@"buyNum"];
    [cell.imageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://120.76.162.124:8083%@", self.shopArrM[indexPath.section][indexPath.row][@"PictureURL"]]]];
    
    if (self.allJudge) {
        cell.selectBtn.selected = YES;
    } else {
        cell.selectBtn.selected = NO;
    }
    
    [cell.addBtn addTarget:self action:@selector(clickAddBtn:) forControlEvents:UIControlEventTouchUpInside];
    [cell.subBtn addTarget:self action:@selector(clickSubBtn:) forControlEvents:UIControlEventTouchUpInside];
    [cell.selectBtn addTarget:self action:@selector(clickSelectBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.cellArrM addObject:cell];
    return cell;
}

#pragma mark - UITableView Delegate 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 150;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ShopCartHeaderCell *shopCartHeader = [ShopCartHeaderCell loadHeaderView];
    shopCartHeader.titleLabel.text = self.shopArrM[section][0][@"MerchantName"];
    shopCartHeader.selectBtn.tag = section;
    if (self.allJudge) {
        shopCartHeader.selectBtn.selected = YES;
    } else {
        shopCartHeader.selectBtn.selected = NO;
    }
    [shopCartHeader.selectBtn addTarget:self action:@selector(clickHeaderSelectBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerArrM addObject:shopCartHeader];
    return shopCartHeader;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ShopMainViewController *shopMainVC = [[ShopMainViewController alloc] init];
    shopMainVC.xingYingShopID = self.shopArrM[indexPath.section][indexPath.row][@"Id"];
    
    [self.navigationController pushViewController:shopMainVC animated:YES];
}

- (void)clickAddBtn:(UIButton *)sender {
    ShopCartCell * cell = (ShopCartCell *)[[sender superview] superview];
    NSIndexPath * path = [self.tableView indexPathForCell:cell];
    cell.buyNum.text = [NSString stringWithFormat:@"%ld", [cell.buyNum.text integerValue] + 1];

    [self.shopArrM[path.section][path.row] setValue:cell.buyNum.text forKey:@"buyNum"];
    
    [ReadLoginData saveShopDataToLocal:self.shopArrM];
    
    [self totalPrice];
}

- (void)clickSubBtn:(UIButton *)sender {
    ShopCartCell * cell = (ShopCartCell *)[[sender superview] superview];
    NSIndexPath * path = [self.tableView indexPathForCell:cell];
    cell.buyNum.text = [NSString stringWithFormat:@"%ld", [cell.buyNum.text integerValue] - 1];
    if ([cell.buyNum.text isEqualToString:@"-1"]) {
        cell.buyNum.text = @"0";
    }
    
    [self.shopArrM[path.section][path.row] setValue:cell.buyNum.text forKey:@"buyNum"];
    
    [ReadLoginData saveShopDataToLocal:self.shopArrM];
    
    [self totalPrice];
}

- (void)clickSelectBtn:(UIButton *)sender {
    ShopCartCell * cell = (ShopCartCell *)[[sender superview] superview];
    NSIndexPath * path = [self.tableView indexPathForCell:cell];
    ShopCartHeaderCell *shopCartHeader = self.headerArrM[path.section];
    NSLog(@"%ld", path.row);
    cell.selectBtn.selected = !cell.selectBtn.selected;
    if (cell.selectBtn.selected) {
        NSInteger i = 0;
        for (ShopCartCell *cell in self.cellArrM) {
            
            if (cell.selectBtn.selected) {
                continue;
            }
            i ++;
        }
        if (i == 0) {
            self.allJudge = YES;
            self.toolBar.selectButton.selected = YES;
            shopCartHeader.selectBtn.selected = YES;
        }
        i = 0;
        for (ShopCartCell *cell in self.cellArrM) {
            NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
            if (indexPath.section == path.section) {
                if (cell.selectBtn.selected) {
                    continue;
                }
                i ++;
            }
        }
        if (i == 0) {
            shopCartHeader.selectBtn.selected = YES;
        }
    } else {
        self.allJudge = NO;
        self.toolBar.selectButton.selected = NO;
        shopCartHeader.selectBtn.selected = NO;
    }
    
    [self totalPrice];
}

- (void)clickHeaderSelectBtn:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    NSLog(@"%ld", sender.tag);
    if (sender.selected) {
        NSInteger i = 0;
        for (ShopCartCell *cell in self.cellArrM) {
            NSIndexPath *indexPaht = [self.tableView indexPathForCell:cell];
            if (indexPaht.section == sender.tag) {
                cell.selectBtn.selected = YES;
            }
            if (cell.selectBtn.selected) {
                continue;
            }
            i ++;
        }
        if (i == 0) {
            self.allJudge = YES;
            self.toolBar.selectButton.selected = YES;
        }
    } else {
        self.allJudge = NO;
        self.toolBar.selectButton.selected = NO;
        for (ShopCartCell *cell in self.cellArrM) {
            NSIndexPath *indexPaht = [self.tableView indexPathForCell:cell];
            if (indexPaht.section == sender.tag) {
                cell.selectBtn.selected = NO;
            }
        }
    }
    [self totalPrice];
}

@end
